//closure, avoid polluting global scope, ensure `$` maps to `jQuery` object.
(function ($) {

    //========================= SETTINGS ==========================//

    //========================= PRIVATE ==========================//

    var $window = $(window);
    
    var $container;
    var blitter;
    
    var $currentProductId = null;
    var $currentProduct;
    var $previousProduct;
    var direction = 1;
    
    var $productGroups = [];
    var $imageQueue = [];
    
    var started = false;
    
    var imageLoadSignal = new signals.Signal();
    
    var startLoadTime = 0;
    var endLoadTime = 0;
    var minLoadTime = 2500;
    
    function createProductGroups() {
    	
    	// add images to queue
    	$('.productGroup').each(function(index, value) { 
    		$(value).find('img').each(function(index, value) {
    			$imageQueue.push($(value));
    		});
		});
		$('.productsLineUp').each(function(index, value) { 
    		$(value).find('img').each(function(index, value) {
    			$imageQueue.push($(value));
    		});
		});
		
    	$('.productGroup').each(function(index, value) { 
			$productGroups.push($(value));
		});
    }
    
    function changeToProduct(id) {
		hasher.setHash(id); //change hash value (generates new history record)
    }
	
    
    function validateProductID(id) {
    	for(var i = 0; i<$productGroups.length; i++) {
    		var idName = id;
    		var product = $productGroups[i];
    		if(product.attr('data-product-id')==idName) {
    			return true;
    		}
    	}
    	return false;
    }
	//handle hash changes
	function handleChanges(newHash, oldHash){
		
    	// track product as page
    	//_gaq.push(['_trackPageview', hasher.getBaseURL()+'/'+hasher.getHash()]);
		
	    if(!validateProductID(newHash)) {
    		showProductGroup($productGroups[0].attr('data-product-id'));
    		return;
    	}
	    if(oldHash) {
	    	showProductGroup(newHash, false);
	    }else{
	    	showProductGroup(newHash, true);
	    }
	}	
	
	//handle hash changes
	function handleChangesInit(newHash){
		hasher.initialized.remove(handleChangesInit);
		if(newHash && validateProductID(newHash)) {
    		handleChanges(newHash);
    	}else{
    		changeToProduct($productGroups[0].attr('data-product-id'));
    	}
	}
    
    function showProductGroup(id, snap) {
    	
    	
    	for(var i = 0; i<$productGroups.length; i++) {
    		var idName = id;
    		var product = $productGroups[i];
    		if(product.attr('data-product-id')==idName) {
    			$currentProductId = idName;
    			$previousProduct = $currentProduct;
    			$currentProduct = product;
    			$currentProduct.show();
    			if($previousProduct) animateOutProduct(false);
    			if(started) animateInProduct(snap);
    		}
    		
    	}
    	
    	
    	for(var i = 0; i<$productGroups.length; i++) {
    		var product = $productGroups[i];
    		if(product!=$previousProduct && product!=$currentProduct) {
				product.hide();
			}
    	}
    	
    }
	
    function getNextProductId() {
    	for(var i = 0; i<$productGroups.length; i++) {
    		var product = $productGroups[i];
    		var nextProduct = ((i+1)>=$productGroups.length) ? $productGroups[0] : $productGroups[i+1];
    		if(product.attr('data-product-id')==$currentProductId) {
    			return nextProduct.attr('data-product-id');
    		}
    	}
    	return null;
    }
    
    function getPrevProductId() {
    	for(var i = 0; i<$productGroups.length; i++) {
    		var product = $productGroups[i];
    		var prevProduct = ((i-1)<0) ? $productGroups[$productGroups.length-1] : $productGroups[i-1];
    		if(product.attr('data-product-id')==$currentProductId) {
    			return prevProduct.attr('data-product-id');
    		}
    	}
    	return null;
    }
    
    function gotoNextProduct() {
    	direction = 1;
    	changeToProduct(getNextProductId());
    }
    
    function gotoPrevProduct() {
    	direction = 0;
    	changeToProduct(getPrevProductId());
    }
    
    function onLeftButtonClick(e) {
    	e.preventDefault();
    	gotoPrevProduct()
    }
    
    function onRightButtonClick(e) {
    	e.preventDefault()
    	gotoNextProduct();
    }
    
    function onPackClick(e) {
    	direction = calculateDirection($(e.target).parent().attr('data-product-id'));
    	changeToProduct($(e.target).parent().attr('data-product-id'));
		//window.scrollTo(0,0);
		window.parent.window.scrollTo(0,0);
        return false;
    }
    
    function calculateDirection(id) {
    	var foundThisId = false;
    	for(var i = 0; i<$productGroups.length; i++) {
    		var product = $productGroups[i];
    		if(product.attr('data-product-id')==id) {
    			foundThisId = true;
    		}
    		if(product.attr('data-product-id')==$currentProductId) {
    			if(foundThisId) {
    				return 0;
    			}else{
    				return 1;
    			}
    		}
    		
    	}
    	return 1;
    }
    
   	function animateInProductLineUp() {
   		
   		$('.productsLineUp').show();
   		/*
   		
   		$('.productsLineUp').css('margin-bottom', -100).delay(200).show().animate({
			opacity: 1,
			marginBottom: '0px'
		}, 1500, 'easeInOutQuart', function() {
			// Animation complete.
		});
		*/
   	}
   	
   	function animateInProduct(snap) {
   		
   		var skipOpacity = false;
   		
   		// OVERRIDE SNAP
   		if ( $.browser.msie && $.browser.version<=7) {
  			snap = true;
		}
		
		// TEST FOR SKIP OPACITY
   		if ( $.browser.msie && $.browser.version<=8) {
  			skipOpacity = true;
		}
   		
   		// ANIMATE BACKGROUND
   		var productBackgroundColor = $currentProduct.attr('data-product-background-color');
		if(snap) {
			$('.productsBackground').css('background-color', productBackgroundColor);
		}else{
			$('.productsBackground').animate( { backgroundColor: productBackgroundColor, queue: false }, 300);
		}
		
		// UPDATE PACK LINE UP
		$('.productsLineUpPackBG').css('background-position', '1px -51px');
		$('.productsLineUpPackBG[data-product-id='+$currentProductId+']').css('background-position', '1px 0px');
   		
   		var marginLeftStart = 400;
   		var animateObject = {
   			marginLeft: '0px'
   		};
   		if(skipOpacity==false) {
   			animateObject.opacity = 1;
   		}else{
   			marginLeftStart = 900;
   		}
   		
   		
   		if(direction==1 && snap==false) {
   			
   			if(skipOpacity==false) {
   				$currentProduct.find('.productImage').css('opacity', 0);
   				$currentProduct.find('.productInfo').css('opacity', 0);
   			}
   		
	   		$currentProduct.find('.productImage').css('margin-left', marginLeftStart).delay(300).show().animate(animateObject, 400, 'easeInOutQuart');
	   		$currentProduct.find('.productInfo').css('position', 'inline-block').css('margin-left', marginLeftStart).delay(400).show().animate(animateObject, 400, 'easeInOutQuart');
			
		}else if(snap==false){
			
			if(skipOpacity==false) {
   				$currentProduct.find('.productInfo').css('opacity', 0);
   				$currentProduct.find('.productImage').css('opacity', 0);
   			}
	   		
	   		$currentProduct.find('.productInfo').css('position', 'inline-block').css('margin-left', -marginLeftStart).delay(300).show().animate(animateObject, 400, 'easeInOutQuart');
			$currentProduct.find('.productImage').css('margin-left', -marginLeftStart).delay(400).show().animate(animateObject, 400, 'easeInOutQuart');
			
		}else{
			
			if(skipOpacity==false) {
   				$currentProduct.find('.productInfo').css('opacity', 1);
   				$currentProduct.find('.productImage').css('opacity', 1);
   			}
			
			$currentProduct.find('.productInfo').css('position', 'inline-block').css('margin-left', 0).show();
			$currentProduct.find('.productImage').css('margin-left', 0).show();
			
		}
		
		// ANIMATE IN LIKE BUBBLE
		
		if(snap==false) {
			
			if(skipOpacity) {
		   		 setTimeout($.proxy(function() {
				    $currentProduct.find('.productsLoveBubble').show();
				  }, this), 800);
			}else{
				$currentProduct.find('.productsLoveBubble').css('opacity', 0).delay(800).show().animate({
						opacity: 1
				}, 400, 'easeInOutQuart');
			}
			
		}else{
			if(skipOpacity) {
				$currentProduct.find('.productsLoveBubble').show();
			}else{
				$currentProduct.find('.productsLoveBubble').css('opacity', 1).show();
			}
		}
			
   		
   	}
   	
   	function animateOutProduct(snap) {
   		
   		var skipOpacity = false;
   		
   		// OVERRIDE SNAP
   		if ( $.browser.msie && $.browser.version<=7) {
  			snap = true;
		}
   		
   		// TEST FOR SKIP OPACITY
   		if ( $.browser.msie && $.browser.version<=8) {
  			skipOpacity = true;
		}
		
		var animateObject = {};
   		if(skipOpacity==false) {
   			animateObject.opacity = 0;
   		}
   		
   		// ANIMATE OUT LIKE BUBBLE
   		if(snap==false && skipOpacity==false) {
   			
	   		$previousProduct.find('.productsLoveBubble').delay(0).animate({
					opacity: 0
			}, 200, 'easeInOutQuart', function(e) {
				// Animation complete.
				$(this).hide();
			});
			
		}else{
			
			if(skipOpacity==false) {
				$previousProduct.find('.productsLoveBubble').css('opacity', 0);
			}
			$previousProduct.find('.productsLoveBubble').hide();
		}
   		
   		if(direction==1 && snap==false) {
   			
   			animateObject.marginLeft = (skipOpacity) ? '-900px' : '-400px';
   			
	   		$previousProduct.find('.productImage').delay(0).animate(animateObject, 400, 'easeInOutQuart', function() {
				// Animation complete.
				$(this).hide();
			});
	   		
	   		$previousProduct.find('.productInfo').delay(100).animate(animateObject, 400, 'easeInOutQuart', function() {
				// Animation complete.
				$(this).hide();
				$previousProduct.hide();
			});
		
		}else if(snap==false){
			
   			animateObject.marginLeft = (skipOpacity) ? '900px' : '400px';
	   		
	   		$previousProduct.find('.productInfo').delay(0).animate(animateObject, 400, 'easeInOutQuart', function() {
				// Animation complete.
				$(this).hide();
			});
			
			$previousProduct.find('.productImage').delay(100).animate(animateObject, 400, 'easeInOutQuart', function() {
				// Animation complete.
				$(this).hide();
				$previousProduct.hide();
			});
			
		}else{
			
			if(skipOpacity==false) {
				$previousProduct.find('.productInfo').css('opacity', 0);
				$previousProduct.find('.productImage').css('opacity', 0);
			}
			
			$previousProduct.find('.productInfo').css('margin-left', '400px').hide();
			$previousProduct.find('.productImage').css('margin-left', '400px').hide();
			
		}
		
		
   	}
   	
   	function initAnimation() {
   	}
   	
   	function start() {
		
		started = true;
		
		
		if(blitter) {
			blitter.stop();
			$(blitter.getContainer()).remove();
		}
		
		 $('.productsLoaderContainer').hide();
		 $('.productsLeftButton').show().click(onLeftButtonClick);
		 $('.productsRightButton').show().click(onRightButtonClick);
		 $('.productsLineUpPackImage').show().click(onPackClick);
		 
		 animateInProductLineUp();
		 animateInProduct(true);
		 
		 alignProductPackLineUp();
		 
		 // should only fade in if css3 is available
		 $('#productsContainer .productsBackground').css('opacity', '1');
		 
   	}
   	
   	function alignProductPackLineUp() {
   		var fullWidth = $("#productsContainer").width();
   		var lineUpWidth = $('.productsLineUp').width();
   		var xVal = Math.round((fullWidth-lineUpWidth)/2);
   		$('.productsLineUp').css('left', xVal);
   	}
   	
   	function startLoadingAnimation() {
   		
   		var animationImg = $('#productsContainer .gifLoader').attr('data-img');
   		
   		blitter = new Blitter({
								target : $('#productsContainer .gifLoader')[0],
								resource : animationImg,
								width : 38,
								height: 38,
								frameRate : 24,
								delay: 2000
							});    
   	}
   	
   	function loadImages() {
   		$("#productsContainer").imagesLoaded(function($images, $proper, $broken ){
            imageLoadSignal.dispatch('complete');
		});
   	}
   	
   	function onImageLoadComplete(){
   		endLoadTime = new Date().getTime();
   		var timeDiff = endLoadTime-startLoadTime;
   		var delayTime = Math.max(minLoadTime-timeDiff, 0);
   		setTimeout(start, delayTime);
	}
   
    //========================= PUBLIC ==========================//

    //========================= INIT ==========================//

    function init() {
    	
    	startLoadingAnimation();
    	
    	// HIDE THINGS
    	$('.productsLeftButton').hide();
    	$('.productsRightButton').hide();
    	$('.productsLineUpPackImage').hide();
    	$('.productInfo').hide();
    	
    	
    	if($('#productsContainer').length>0) {
    		
    		startLoadTime = new Date().getTime();
    		
	    	createProductGroups();
	    	
         	hasher.changed.add(handleChanges); //add hash change listener
		 	hasher.initialized.add(handleChangesInit); //add initialized listener (to grab initial value in case it is already set)
		 	hasher.init(); //initialize hasher (start listening for history changes)
    		
	    	imageLoadSignal.add(onImageLoadComplete);
	    	loadImages();
    	
    	}
		
    	
	     
    }

    $(window).ready(init);

} (jQuery));